package com.faithbj.process.impl;

import com.faithbj.common.model.User;
import com.google.common.base.Function;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Lists;
import org.jbpm.task.service.UserGroupCallback;

import javax.persistence.Query;
import java.util.List;
import java.util.Set;

/**
 * User: xiongyuanwei
 * Date: 12-7-21
 * Time: 下午10:27
 */
public class UserGroupCallbackImpl implements UserGroupCallback {

    private Set<String> groups = ImmutableSet.of("outer", "inner");
    private Query usersQuery = ProcessEntityManagerHolder.getProcessEntityManager()
            .createQuery("select u from User u");

    private Function<User, String> usernameExtractor = new Function<User, String>() {
        @Override
        public String apply(User user) {
            return user.getUsername();
        }
    };

    @SuppressWarnings("unchecked")
    @Override
    public boolean existsUser(String userId) {
        List<User> userObjs = usersQuery.getResultList();
        List<String> usernames = Lists.newArrayList(Lists.transform(userObjs, usernameExtractor));
        usernames.add("Administrator");
        return usernames.contains(userId);
    }

    @Override
    public boolean existsGroup(String groupId) {
        return groupId != null && groups.contains(groupId);
    }

    @Override
    public List<String> getGroupsForUser(String userId, List<String> groupIds, List<String> allExistingGroupIds) {
        return Lists.newArrayList(groups);
    }
}
